# -*- coding: utf-8  -*-
"""
Bot to create redirects. This version create redirect to title containing accented letters and various special chars
 

Command-line arguments:
 
    -file       Work on all pages listed in a text file.
                Argument can also be given as "-file:filename".
 
    -cat        Work on all pages which are in a specific category.
                Argument can also be given as "-cat:categoryname".
 
    -ref        Work on all pages that link to a certain page.
                Argument can also be given as "-ref:referredpagetitle".
 
    -links      Work on all pages that are linked from a certain page.
                Argument can also be given as "-link:linkingpagetitle".
    -start      Work on all pages on the home wiki, starting at the named
                page.
 
    -page       Work on a single page.
 
    -namespace  Run over especific namespace.
                Argument can also be given as "-namespace:100" or
                "-namespace:Image".
 
    -always     Don't prompt to make changes, just do them.
"""

import time, re
import wikipedia, pagegenerators
 
msg = {
    'en': u'Robot: Create redirect to [[%s]]',
    'es': u'Bot: Creando redirección a [[%s]]',
    'it': u'Bot: Creo redirect a [[%s]]',
    'fr': u'Robot : Creation redirect vers [[%s]]',
    'pt': u'Bot: Criando redirect para [[%s]]',
    }
 

def generar_titulo(original):
    lista_old = u'ñÑ×ẢĄÀÁÂÃÄÅǍȦǠẠẬẶāąảàáâãäåąǎȧǡạậặăĒĘĖẸỆÈÉÊËĚēęėẹệèéêëěəĪỊİÌÍÎÏǏĮīɨịìíîïǐıŌỔȮȰȱƠÒÓÔÕÖØǑƏōổȯỌọỘộơòóôõöøǒőŪŲǙÙÚÛÜǓỤūųǚùúûüǔụŭḂḄßḃḅĊÇČ¢ćċçčḌḊĎÐĐḍḋđďðĠǤǦġǥǧğĹḶŁĽḸḸĺḷłľḹḹṄṆŇṅṇńňṘŘṚṜřṛṝṙŞṠṢṦṤṨṦŚ$şṡṣṧṥṩŠšṧşŦŤṪṬŧťṫṭţẎỴẏỵÿýŻẒŽżẓžżźḞḟĦħȞȟḢḣḤḥƗįǰḲḳǨǩṀṁṂṃṖṗƯưṾṿẆẇẈẉҲҳẊẋ,;–ºª\\/-.'
    lista_new = u'nNxAAAAAAAAAAAAAAaaaaaaaaaaaaaaaaaEEEEEEEEEEeeeeeeeeeeeIIIIIIIIIiiiiiiiiiOOOOOOOOOOOOOoooooooooooooooooUUUUUUUUUuuuuuuuuuuBBBbbCCCcccccDDDDDdddddGGGggggLLLLLLllllllNNNnnnnRRRRrrrrSSSSSSSSSssssssssssTTTTtttttYYyyyyZZZzzzzzFfHhHhHhHhIijKkKkMmMmPpUuVvWWWwXx           '
    #lista_todasjuntas_old =
    #lista_todasjuntas_new = 

    nueva = []
    i = 0
    while i<len(lista_old):
        nueva_posible = original.replace(lista_old[i], lista_new[i], 1)
        if nueva_posible <> original:
            nueva.append(nueva_posible)
        i += 1

    for x in nueva:
        i = 0
        while i<len(lista_old):
            nueva_posible = x.replace(lista_old[i], lista_new[i], 1)
            if nueva_posible <> x and nueva_posible <> original and nueva_posible not in nueva:
                nueva.append(nueva_posible)
            i += 1

    return nueva

   
def checkRedirect(page):
    try:
        text = page.get()
    # Double redirect!
    except wikipedia.IsRedirectPage:
        return 1
    # Break Redirect!
    except wikipedia.NoPage:
        return 2
    # Something-else! :-)
    except wikipedia.Error:
        return 2
    text = text.lower()
    # Checking the text in the page.
    res = re.findall(r'([^>]#redirec(ción|t)\s*?\[\[)', text)
    if res == []:
        return 0
    else:
        return 1
 
def saveNumbers(ediciones, tipo):
    """ Guarda el número de ediciones en un fichero """
    if ediciones==0:
        if tipo=='c':
            f = open('zzcrred_created.txt')
        elif tipo=='e':
            f = open('zzcrred_existed.txt')
        elif tipo=='t':
            f = open('zzcrred_total.txt')

        return int(f.read())
    
    else:
        if tipo=='c':
            f = open('zzcrred_created.txt', 'w')
        elif tipo=='e':
            f = open('zzcrred_existed.txt', 'w')
        elif tipo=='t':
            f = open('zzcrred_total.txt', 'w')
        f.write(str(ediciones))

    f.close()

class CapitalizeBot:
    def __init__(self, generator, acceptall, msg):
        self.generator = generator
        self.acceptall = acceptall
        self.msg = msg
 
    def run(self):
        global stat_created, stat_existed, stat_total, page_t
        
        #-- put before the for..in so its not generated at each loop
        stat_created = saveNumbers(0, 'c') #number of created redirects
        stat_existed = saveNumbers(0, 'e') #redirect already existed
        stat_total   = saveNumbers(0, 't') #total parsed pages

        for page in self.generator:
            page_t = page.title()
            
            #stat show one time out of 10 pages : at the 60th, 160th, etc.
            if (stat_total % 200 == 0):
                wikipedia.output(u'\03{lightgreen}  Status: working on \03{lightblue}%s\03{default}.\n  \03{lightyellow}%s\03{default} pages created, \03{lightyellow}%s\03{default} already existed, \03{lightyellow}%s\03{default} pages parsed.\03{default}' % (page_t, stat_created, stat_existed, stat_total))
                saveNumbers(stat_created, 'c')
                saveNumbers(stat_existed, 'e')
                saveNumbers(stat_total, 't')
             
            stat_total += 1

            site = wikipedia.getSite()

            if '(desamb' in page_t:# salir si es una página de desambiguación
                wikipedia.output(u'%s parece una página de desambiguación (salir).\n' % page_t)
                continue
            
            try:
                lista_redirects = generar_titulo(page_t)
                cont = 0
                while cont<len(lista_redirects):
                    lista_redirects[cont] = wikipedia.Page(site, lista_redirects[cont])
                    cont += 1
                
                #redirectpage = wikipedia.Page(site, getRedirectTitle(table, page_t) )
            except wikipedia.InvalidTitle:
                wikipedia.output(u'\n\03{lightred}Invalid title!\03{default}')
                continue
            
            for redirectpage in lista_redirects:
                if checkRedirect(page)==2:# error?
                    continue

                #is the redirect title the same as the original title ?
                #if page.title() == redirectpage.title():
                #    continue #nothing to do, no output
                    
                #does the redirect we want to create already exist ?            
                if redirectpage.exists():
                    stat_existed += 1                
                    wikipedia.output(u'\03{lightyellow}%s\03{default} already exists, skip!' % redirectpage.title())
                    continue
     
                if checkRedirect(page):#is the page we're working on a redirect? if true, we'll work on its target            
                    page_t = page.getRedirectTarget().title()

                # Show the title of the page we're working on.
                wikipedia.output(u"\n>>> \03{lightpurple}%s\03{default} <<<" % page_t)
                if checkRedirect(page):
                    wikipedia.output(u" (from page %s)" % page.title())
                #wikipedia.output(u'Creating \03{lightyellow}%s\03{default}...' % redirectpage.title())
                created = True
                if not self.acceptall:
                    choice = wikipedia.inputChoice(
                            u'Do you want to create the redirect?',
                            ['Yes', 'No', 'All'], ['y', 'N', 'a'], 'N')
                    if choice in ['a', 'A']:
                        self.acceptall = True
                if self.acceptall or choice in ['y', 'Y']:
                    try:
                        comment = wikipedia.translate(wikipedia.getSite(), self.msg) % page_t
                        if page_t.startswith('Categor'):# dos puntos a las categorías
                            page_t = u':' + page_t
                        redirectpage._putPage(u"#REDIRECCIÓN [[%s]]" % page_t, comment, newPage = True)
                    except wikipedia.EditConflict:
                        wikipedia.output(u"An edit conflict has occurred. Skip!...")
                        continue
                    except wikipedia.LockedPage:
                        wikipedia.output(u"page was protected against creation. Skip!...")
                        continue
                stat_created += 1
 
def main():
    gen = None
    source = None
    textfilename = None
    categoryname = None
    pageNames = []
    referredPageName = None
    acceptall = True
    namespaces = []
    startpage = None
 
    for arg in wikipedia.handleArgs():
        if arg.startswith('-file'):
            if len(arg) == 5:
                textfilename = wikipedia.input(u'Please enter the filename:')
            else:
                textfilename = arg[6:]
            source = 'textfile'
        elif arg.startswith('-cat'):
            if len(arg) == 4:
                categoryname = wikipedia.input(
                               u'Please enter the category name:')
            else:
                categoryname = arg[5:]
            source = 'category'
        elif arg.startswith('-page'):
            if len(arg) == 5:
                pageNames.append(wikipedia.input(
                                 u'Which page do you want to change?'))
            else:
                pageNames.append(arg[6:])
            source = 'singlepage'
        elif arg.startswith('-ref'):
            if len(arg) == 4:
                referredPageName = wikipedia.input(
                                   u'Links to which page should be processed?')
            else:
                referredPageName = arg[5:]
            source = 'ref'
        elif arg.startswith('-start'):
            if len(arg) == 6:
                firstPageTitle = wikipedia.input(
                                 u'Which page do you want to change?')
            else:
                firstPageTitle = arg[7:]
            source = 'allpages'
        elif arg == '-always':
            acceptall = True
        elif arg.startswith('-namespace:'):
            try:
                namespaces.append(int(arg[11:]))
            except ValueError:
                namespaces.append(arg[11:])
        else:
            commandline_replacements.append(arg)
 
    if source == 'textfile':
        gen = pagegenerators.TextfilePageGenerator(textfilename)
    elif source == 'category':
        cat = catlib.Category(wikipedia.getSite(), categoryname)
        gen = pagegenerators.CategorizedPageGenerator(cat)
    elif source == 'singlepage':
        pages = [wikipedia.Page(wikipedia.getSite(), pageName)
                 for pageName in pageNames]
        gen = iter(pages)
    elif source == 'allpages':
        namespace = wikipedia.Page(wikipedia.getSite(),
                                   firstPageTitle).namespace()
        gen = pagegenerators.AllpagesPageGenerator(firstPageTitle, namespace)
    elif source == 'ref':
        referredPage = wikipedia.Page(wikipedia.getSite(), referredPageName)
        gen = pagegenerators.ReferringPageGenerator(referredPage)
    elif source == None or len(commandline_replacements) not in [0, 2]:
        wikipedia.stopme()
        wikipedia.showHelp(u'capitalize_redirects')
        sys.exit()
    if namespaces != []:
        gen =  pagegenerators.NamespaceFilterPageGenerator(gen, namespaces)
    preloadingGen = pagegenerators.PreloadingGenerator(gen, pageNumber = 200)
    bot = CapitalizeBot(preloadingGen, acceptall, msg)
    bot.run()
 
if __name__ == "__main__":
    try:
        main()
    finally:
        saveNumbers(stat_created, 'c')
        saveNumbers(stat_existed, 'e')
        saveNumbers(stat_total, 't')
        
	parada = wikipedia.Page(wikipedia.getSite(), u"Usuario:Muro Bot/Avisos/Redirecciones")
        parada.put(u"* %s\n* %s\n* %s\n\n''%s''\n\n~~~~" % (stat_created, stat_existed, stat_total, page_t), u"Bot: Aviso (%s)" % stat_created)
        wikipedia.stopme()
